/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.oper.RemoteClient;

import java.io.IOException;
import java.net.SocketException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;

/**
 *
 * @author hxg
 */
public class TelnetOper extends RemoteClientOper {

    TelnetClient tc;

    public TelnetOper(String ip, int port) {
        super(ip, port);
    }

    @Override
    public void init() {
        tc = new TelnetClient();
        try {
            tc.connect(ip, port);
            is = tc.getInputStream();
            os = tc.getOutputStream();
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            tc.addOptionHandler(ttopt);
            tc.addOptionHandler(echoopt);
            tc.addOptionHandler(gaopt);
        } catch (InvalidTelnetOptionException ex) {
            Logger.getLogger(TelnetOper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SocketException ex) {
            Logger.getLogger(TelnetOper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TelnetOper.class.getName()).log(Level.SEVERE, null, ex);
        }
        startReader();
    }

    @Override
    public void close() {
        if (tc != null) {
            try {
                tc.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(TelnetOper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        is = null;
        os = null;
    }
}
